package com.dididoctor.patient.Activity.OneToOneChat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Bean.MessageChatBean;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.MV.BasePresenter;
import com.netease.nimlib.sdk.InvocationFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.AudioAttachment;
import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 项目名称：Psd
 * 类描述：一对一聊天
 * 创建人：张强
 * 创建时间：2015/7/20 17:39
 * 修改人：
 * 修改时间：2015/7/20 17:39
 * 修改备注：
 */
public class OneToOneChatPresenter extends BasePresenter {

    private OneToOneChatView view = null;
    private MyBroadcastReciver myBroadcastReciver = null;
    private Context mcontext;
    //广播
    private boolean isstartbroadcast = false;
    private List<MessageChatBean> listData;
    private long newTime = System.currentTimeMillis();

    public OneToOneChatPresenter(Context context, OneToOneChatView view) {
        super(context, view);
//        myBroadcastReciver = new MyBroadcastReciver(context, view, FriendId, FriendName);
        this.view = view;
        this.mcontext = context;
    }

    /**
     * 加载历史消息
     *
     * @param sessionId
     */
    public void loadData(String sessionId) {
        InvocationFuture<List<IMMessage>> listInvocationFuture = NIMClient.getService(MsgService.class).pullMessageHistory(MessageBuilder.createEmptyMessage(sessionId, SessionTypeEnum.P2P, 0), ConstantValue.LOAD_MESSAGE_COUNT, false);
        listInvocationFuture.setCallback(new RequestCallback<List<IMMessage>>() {
            @Override
            public void onSuccess(List<IMMessage> imMessages) {
                listData = new ArrayList<MessageChatBean>();
                for (IMMessage map : imMessages) {

                    MessageChatBean cm = new MessageChatBean();
                    if (newTime - map.getTime() > 180000) {
                        cm.setIsshowTime(true);
                        newTime = map.getTime();
                    } else {
                        cm.setIsshowTime(false);
                    }
                    cm.setCreateTime(map.getTime() + "");

                    cm.setId(map.getUuid());
                    cm.setContent(map.getContent());
                    cm.setMsgCode(map.getMsgType() + "");

                    if (map.getSessionId() == map.getFromAccount()) {
                        cm.setSenduid(map.getSessionId());
                        cm.setTouid(Token.getId());
                    } else {
                        cm.setSenduid(Token.getId());
                        cm.setTouid(map.getSessionId());
                    }

                    FileAttachment attachment = (FileAttachment) map.getAttachment();


                    switch (map.getMsgType()) {
                        case text:
                            if (MsgDirectionEnum.In.getValue() == map.getDirect().getValue()) {
                                cm.setPosition(MessageChatBean.LEFT_TEXT + "");
                            } else {
                                cm.setPosition(MessageChatBean.RIGHT_TEXT + "");
                            }
                            break;
                        case image:
                            if (MsgDirectionEnum.In.getValue() == map.getDirect().getValue()) {
                                cm.setPosition(MessageChatBean.LEFT_IMG + "");
                            } else {
                                cm.setPosition(MessageChatBean.RIGHT_IMG + "");
                            }
                            if (attachment != null) {
                                cm.setfId(attachment.getUrl());
                                cm.setContent(attachment.getDisplayName() + "");
                            }

                            break;
                        case audio:
                            if (MsgDirectionEnum.In.getValue() == map.getDirect().getValue()) {
                                cm.setPosition(MessageChatBean.LEFT_VOICE + "");
                            } else {
                                cm.setPosition(MessageChatBean.RIGHT_VOICE + "");
                            }
                            if (attachment != null) {
                                cm.setfId(attachment.getUrl());
                                long duration = ((AudioAttachment) attachment).getDuration();
                                int seconds = (int) duration / 1000;
                                cm.setContent("[对讲]:" + seconds);
                            }
                            break;
                        default:
                            break;
                    }
                    listData.add(cm);
                }
                Collections.reverse(listData);
//                if (listData != null) {
//                    if (Page == 1) {
//                        view.fillData(listData);
//                    } else {
//                        view.addData(listData);
//                    }
//                }
                view.fillData(listData);
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }


    /**
     * 开始接收会话消息
     */
    public void startReceiverChatMessage() {
        // 接收会话的广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("getOneToOnepush");
        mcontext.registerReceiver(myBroadcastReciver, intentFilter);
        isstartbroadcast = true;
    }

    /**
     * 结束接收会话消息
     */
    public void stopReceiverChatMessage() {
        if (myBroadcastReciver != null) {
            mcontext.unregisterReceiver(myBroadcastReciver);
        }
    }

    /**
     * 发送文本类型的消息
     * text 发生内容
     * teacherId 接受人id
     */
    public void sendTextMsg(String sessionId, String sessionname, String content) {
        //发送的文本
        // 创建文本消息
        IMMessage message = MessageBuilder.createTextMessage(
                sessionId, // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                content // 文本内容
        );

        //发送文本消息
        sendChatMessage(message, sessionId, sessionname);
    }


    //

    /**
     * 发送音频
     *
     * @param
     */
    public void sendSecord(final int seconds, String sessionId, String sessionname, String path) {

        // 创建音频消息
        IMMessage message = MessageBuilder.createAudioMessage(
                sessionId, // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                new File(path), // 音频文件
                seconds // 音频持续时间，单位是ms
        );

        //发送消息
        sendChatVoiceMessage(message, sessionId, sessionname, seconds);
    }

    /**
     * 发送图片类型消息
     *
     * @param path
     */
    public void sendImageFromUri(String sessionId, String sessionname, String path) {
        // 创建图片消息
        IMMessage message = MessageBuilder.createImageMessage(
                sessionId, // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                new File(path), // 图片文件对象
                "[图片]" // 文件显示名字，如果第三方 APP 不关注，可以为 null
        );

        //发送图片消息
        sendImageviewChatMessage(message, sessionId, sessionname);

    }


    /**
     * 发送消息
     *
     * @param message
     * @param sessionId
     * @param sessionname
     */
    private void sendImageviewChatMessage(final IMMessage message, final String sessionId, final String sessionname) {
        NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                MessageChatBean localmessage = new MessageChatBean();
                if (newTime - message.getTime() > 180000) {
                    localmessage.setIsshowTime(true);
                    newTime = message.getTime();
                } else {
                    localmessage.setIsshowTime(false);
                }
                localmessage.setCreateTime(System.currentTimeMillis() + "");
                localmessage.setTouid(sessionId);
                localmessage.setTouName(sessionname);
                localmessage.setContent("[图片]");
                localmessage.setSenduid(Token.getId());
                localmessage.setSenduName(Token.getName());
                localmessage.setPosition(MessageChatBean.RIGHT_IMG + "");
                localmessage.setfId(((FileAttachment) message.getAttachment()).getPath());

                view.append(localmessage);
            }

            @Override
            public void onFailed(int code) {
                if (code == ResponseCode.RES_CHATROOM_MUTED) {
                    view.showToastMessage("用户被禁言");
                } else {
                    view.showToastMessage("消息发送失败：code:" + code);
                }
            }

            @Override
            public void onException(Throwable throwable) {
                view.showToastMessage("消息发送失败！");

            }
        });
    }

    /**
     * 发送语音消息
     *
     * @param message
     * @param sessionId
     * @param sessionname
     * @param seconds
     */
    private void sendChatVoiceMessage(final IMMessage message, final String sessionId, final String sessionname, final int seconds) {
        NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                MessageChatBean localmessage = new MessageChatBean();
                if (newTime - message.getTime() > 180000) {
                    localmessage.setIsshowTime(true);
                    newTime = message.getTime();
                } else {
                    localmessage.setIsshowTime(false);
                }
                localmessage.setCreateTime(System.currentTimeMillis() + "");
                localmessage.setTouid(sessionId);
                localmessage.setTouName(sessionname);
                localmessage.setContent("[对讲]:" + seconds);
                localmessage.setSenduid(Token.getId());
                localmessage.setSenduName(Token.getName());
                localmessage.setfId(((FileAttachment) message.getAttachment()).getPath());
                localmessage.setPosition(MessageChatBean.RIGHT_VOICE + "");
                view.append(localmessage);
            }

            @Override
            public void onFailed(int code) {
                if (code == ResponseCode.RES_CHATROOM_MUTED) {
                    view.showToastMessage("用户被禁言");
                } else {
                    view.showToastMessage("消息发送失败：code:" + code);
                }
            }

            @Override
            public void onException(Throwable throwable) {
                view.showToastMessage("错误代码" + throwable.toString());
            }
        });

    }


    /**
     * 发送文本消息
     *
     * @param message
     * @param sessionId
     * @param sessionname
     */
    private void sendChatMessage(final IMMessage message, final String sessionId, final String sessionname) {
        // 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(MsgService.class).sendMessage(message, true).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                //本地的文本消息
                MessageChatBean Localmessage = new MessageChatBean();
                if (newTime - message.getTime() > 180000) {
                    Localmessage.setIsshowTime(true);
                    newTime = message.getTime();
                } else {
                    Localmessage.setIsshowTime(false);
                }
                Localmessage.setCreateTime(message.getTime() + "");
                Localmessage.setSenduid(Token.getId());
                Localmessage.setSenduName(Token.getName());
                Localmessage.setTouid(sessionId);
                Localmessage.setTouName(sessionname);
                Localmessage.setContent(message.getContent());
                Localmessage.setPosition(MessageChatBean.RIGHT_TEXT + "");
                //界面回显
                view.append(Localmessage);
            }

            @Override
            public void onFailed(int code) {
                if (code == ResponseCode.RES_CHATROOM_MUTED) {
                    view.showToastMessage("用户被禁言");
                } else {
                    view.showToastMessage("消息发送失败：code:" + code);
                }
            }

            @Override
            public void onException(Throwable throwable) {
                view.showToastMessage("错误代码" + throwable.toString());
            }
        });

    }


    private class MyBroadcastReciver extends BroadcastReceiver {
        private OneToOneChatPresenter presenter = null;
        private Context mcontext;
        private OneToOneChatView view = null;
        private String FriendId, FriendName;

        public MyBroadcastReciver(Context context, OneToOneChatView view, String FriendId, String FriendName) {
            this.view = view;
            this.mcontext = context;
            this.FriendId = FriendId;
            this.FriendName = FriendName;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            this.presenter = new OneToOneChatPresenter(mcontext, view);
            String action = intent.getAction();
            if (action.equals("getOneToOnepush")) {
                String tag = intent.getStringExtra("Tag");
                if ("0".equals(tag)) {
                    String capturePath = intent.getStringExtra("capturePath");
                    this.presenter.sendImageFromUri(capturePath, this.FriendId, this.FriendName);
                } else if ("1".equals(tag)) {
                    MessageChatBean message = (MessageChatBean) intent.getSerializableExtra("message");
                    if (message != null) {
                        if ("".equals(message.getPosition()) && message.getPosition() != null) {
                            view.append(message);
                        }

                    }
                }

            }
        }

    }
}
